<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>角色权限</title>
    <link rel="stylesheet" href="../element/latest/element.css" media="all">
    <link rel="stylesheet" href="../vue-table/3.2.1/style.css" media="all">
    <script type="text/javascript" src="../vue/es6-promise.auto.min.js"></script>
    <script type="text/javascript" src="../vue/es6-promise.auto.min.js"></script>
    <script type="text/javascript" src="../vue/browser.min.js"></script>
    <script type="text/javascript" src="../vue/browser-polyfill.min.js"></script>
    <script type="text/javascript" src="../vue/vue.js"></script>
    <script type="text/javascript" src="../vue/axios.js"></script>
    <script type="text/javascript" src="../element/latest/element.js"></script>
    <script type="text/javascript" src="../vue-table/3.2.1/xe-utils.js"></script>
    <script type="text/javascript" src="../vue-table/3.2.1/vxe-table.js"></script>
    <script type="text/javascript" src="../../../editor/assets/drag/js/lib/mc/magicaltool.js"></script>
    <script type="text/javascript" src="../mc/mc-new-vxe-table.js"></script>
    <script type="text/javascript" src="../mc/official-ui.js"></script>
</head>
<body style="">
<div id="magicalDragScene">
    <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="角色管理" name="first">
            <el-form :model="roleForm">
                <el-form-item label="角色名称:" :label-width="roleDialog.formLabelWidth">
                    <el-input v-model="roleForm.name" autocomplete="off" style="width:18%" clearable></el-input>
                </el-form-item>
                <el-button size="small" @click="selectRole">查询</el-button>
                <el-button size="small" type="primary" @click="restRoleForm">重置</el-button>
                <el-button size="small" type="success" @click="insertRole">新增</el-button>
            </el-form>
            <el-table
                :data="roleData"
                style="width: 100%"
                :row-class-name="tableRowClassName">
                <el-table-column label="序号" width="150"
                    type="index">
                </el-table-column>
                <el-table-column
                    label="角色名" width="300"
                    prop="name">
                </el-table-column>
                <el-table-column
                    label="角色KEY"
                    prop="key">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="success"
                            @click="handleEditRole(scope.$index, scope.row)">关联权限
                        </el-button>
                        <el-button
                            size="mini"
                            type="success"
                            @click="handleEditMenu(scope.$index, scope.row)">配置菜单
                        </el-button>
                        <el-button
                            size="mini"
                            type="primary"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--    新增角色模态框-->
            <el-dialog :title="roleDialog.form.uuid == ''?'新增':'修改'" :visible.sync="roleDialog.roleVisible">
                <el-form :model="roleDialog.form" :rules="roleFormRules">
                    <el-form-item v-show="false">
                        <el-input v-model="roleDialog.form.uuid" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称:"  prop="name">
                        <el-input v-model="roleDialog.form.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色KEY:"  prop="key">
                        <el-input v-model="roleDialog.form.key" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="roleDialog.roleVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="insertOrUpdateRole">确 定</el-button>
                </div>
            </el-dialog>
            <!--    配置权限模态框-->
            <el-dialog :title="permissionDialog.title" :visible.sync="permissionDialog.permissionVisible">
                <el-transfer
                    v-model="permissionDialog.hasPermissions"
                    :data="projectObj.data.permissions"
                    :props="{
                        key: 'uuid',
                        label: 'name'
                    }"
                    filterable
                    :titles="permissionDialog.titles"
                >
                </el-transfer>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="permissionDialog.permissionVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="updateRolePermission">确 定</el-button>
                </div>
            </el-dialog>
<!--            菜单模态框-->
            <el-dialog :title="menuDialog.title" :visible.sync="menuDialog.menuVisible">
                <el-tree
                    :data="menuDialog.data"
                    show-checkbox
                    default-expand-all
                    ref="tree"
                    node-key="id"
                    :default-expanded-keys="menuDialog.roleAllFatherMenu"
                    :default-checked-keys="menuDialog.roleHasMenus"
                    :props="defaultProps">
                </el-tree>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="menuDialog.menuVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="updateRoleMenu">确 定</el-button>
                </div>
            </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="接口管理" name="second">
            <el-form :model="permissionForm" >
                <el-form-item label="接口名称:" :label-width="permissionDialog.formLabelWidth">
                    <el-input v-model="permissionForm.name" autocomplete="off" style="width:18%" clearable></el-input>
                </el-form-item>
                <el-button size="small" type="primary" @click="selectPermission">查询</el-button>
                <el-button size="small" type="primary" @click="restPermissionForm">重置</el-button>
                <el-button size="small" type="success" @click="insertPermission">新增</el-button>
            </el-form>
            <el-table
                :data="permissionData"
                style="width: 100%"
                :row-class-name="tableRowClassName">
                <el-table-column
                    type="index"
                    width="150">
                </el-table-column>
                <el-table-column
                    label="姓名"
                    prop="name">
                </el-table-column>
                <el-table-column
                    label="接口地址"
                    prop="urlReg">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="primary"
                            @click="handleEditPermission(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDeletePermission(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageObj.currentPage"
                :page-sizes="pageObj.pageSizes"
                :page-size="pageObj.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageObj.total">
            </el-pagination>
            <!--    新增接口模态框-->
            <el-dialog :title="interfaceDialog.form.uuid == ''?'新增':'修改'" :visible.sync="interfaceDialog.permissionVisible">
                <el-form :model="interfaceDialog.form" :rules="permissionFormRules">
                    <el-form-item v-show="false">
                        <el-input v-model="interfaceDialog.form.uuid" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="接口名称:" :label-width="interfaceDialog.formLabelWidth" prop="name">
                        <el-input v-model="interfaceDialog.form.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="接口地址:" :label-width="interfaceDialog.formLabelWidth" prop="urlReg">
                        <el-input v-model="interfaceDialog.form.urlReg" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="small" @click="interfaceDialog.permissionVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="insertOrUpdatePermission">确 定</el-button>
                </div>
            </el-dialog>
        </el-tab-pane>
    </el-tabs>

</div>
<script>

    var _t = this;
    var Ctor = Vue.extend({
        //提前绑定的变量
        data: function () {
            return {
                tab: "",
                activeName: 'first',
                messageTitle: '',
                // 项目信息
                projectObj:{
                    projectUuid: '',// 项目id
                    data:{
                        roles: [],// 所有角色
                        permissions: [],//所有权限
                        menus: [], //所有菜单
                    }
                },
                pageObj:{
                    currentPage: 1,
                    pageSizes:[15, 20, 30, 50],
                    pageSize:15,
                    total: 0
                },
                roleForm: {
                  name: ''
                },
                permissionForm: {
                    name: ''
                },
                roleData:[],
                // 角色
                roleDialog: {
                    roleVisible: false,
                    formLabelWidth: '100px',
                    form: {
                        uuid: '',
                        name: '',
                        key:''
                    }
                },
                menuDialog: {
                    title: '配置菜单',
                    menuVisible: false,
                    data:[],
                    roleUuid: '',
                    roleAllFatherMenu:[],// 所有tree 父节点
                    roleHasMenus:[],// 拥有菜单
                    checkedMenus:[],// 已经勾选菜单
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                //接口
                interfaceDialog: {
                    permissionVisible: false,
                    formLabelWidth: '100px',
                    form: {
                        uuid: '',
                        name: '',
                        urlReg: ''
                    }
                },
                // 权限
                permissionDialog: {
                    title: '配置权限',
                    titles:['未分配权限', '已分配权限'],
                    permissionVisible: false,
                    roleUuid: '',
                    hasPermissions: [],
                },
                permissionData: [],
                roleFormRules:{
                    name: [
                        { required: true, message: '名称不能为空', trigger: 'change' }
                    ],
                    key: [
                        { required: true, message: 'KEY不能为空', trigger: 'change' }
                    ]
                },
                permissionFormRules:{
                    name: [
                        { required: true, message: '名称不能为空', trigger: 'change' }
                    ],
                    urlReg: [
                        { required: true, message: '地址不能为空', trigger: 'change' }
                    ],
                }
            }
        },
        //页面加载完 会执行方法 可以做一些初始化操作
        mounted: function () {
            this.getProject()
        },
        /*当前页面绑定的方法集合 与布局器节点一一映射即可 参照element ui文档*/
        methods: {
            tabClick:function() {

            },
            getProject:function(){
                var _this = this
                this.$magicaltool.request.axios({
                    method: 'get',
                    url: '/magical_lowcode/manager/page/role',
                    param: {}
                }).then(function (res) {
                    // 处理json数据,解析出角色，拥有权限，所有权限，拥有菜单，所有菜单
                    if (res.code == 0){
                        _this.analysis(res.data)
                    }else{
                        _this.$message({
                            message: '获取项目信息失败',
                            type: 'error'
                        });
                    }
                });
            },
            analysis:function(data) {
                // 角色 权限 菜单
                var projectObj = JSON.parse(data.data);
                this.projectObj.projectUuid = data.projectUuid;
                this.projectObj.data.roles = projectObj.roles||[];
                this.projectObj.data.permissions = projectObj.permissions||[];
                this.projectObj.data.menus = projectObj.menus||[];
                // 所有角色
                this.roleData = this.projectObj.data.roles||[];
                // 所有菜单
                this.menuDialog.data = this.updateJsonPro(this.projectObj.data.menus,'name','label','uuid','id');
                // 所有父菜单节点
                this.menuDialog.roleAllFatherMenu = this.getAllFatherTreeNode(this.menuDialog.data);
                // 处理接口数据 前端分页
                this.permissionData = this.getPagePermissionData(this.pageObj.currentPage,this.pageObj.pageSize,this.projectObj.data.permissions);
            },
            handleClick:function() {
              // console.log(this.activeName)
            },
            insertRole:function(){
              var obj = {
                  uuid: '',
                  name: '',
                  key:''
              }
              this.roleDialog.form = obj
              this.roleDialog.roleVisible = true
            },
            insertPermission:function(){
                var obj = {
                    uuid: '',
                    name: '',
                    urlReg: ''
                }
                this.interfaceDialog.form = obj
                this.interfaceDialog.permissionVisible = true
            },
            handleEdit:function(index, row) {
                var obj = {
                    uuid: '',
                    name: '',
                    key:''
                };
                obj.uuid = row.uuid;
                obj.name = row.name;
                obj.key = row.key;
                this.roleDialog.form = obj;
                this.roleDialog.roleVisible = true
            },
            handleEditPermission:function(index,row){
                var obj = {
                    uuid: '',
                    name: '',
                    urlReg:''
                }
                obj.uuid = row.uuid;
                obj.name = row.name;
                obj.urlReg = row.urlReg;
                this.interfaceDialog.form = obj;
                this.interfaceDialog.permissionVisible = true;
            },
            handleDeletePermission:function(index,row){
                this.$confirm('删除接口, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.updateArrData(this.projectObj.data.permissions,row.uuid,'deletePermission','');
                    this.messageTitle = '删除接口';
                    this.saveCurrectProject();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            handleDelete:function(index, row) {
                this.$confirm('删除角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.updateArrData(this.projectObj.data.roles,row.uuid,'deleteRole','');
                    this.messageTitle = '删除角色';
                    this.saveCurrectProject();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            handleEditRole:function(index, row) {
                this.permissionDialog.roleUuid = row.uuid;
                // role 查找角色权限 projectObj roles
                // 赋值当前角色权限
                this.permissionDialog.hasPermissions = this.getDataFromArr(this.projectObj.data.roles,row.uuid,'rolePermissions');
                this.permissionDialog.permissionVisible = true;
            },
            handleEditMenu:function(index, row) {
                this.menuDialog.roleUuid = row.uuid;
                // 清空菜单所有选择项 单纯清空hasMenus不生效
                this.menuDialog.menuVisible = true;
                this.menuDialog.roleHasMenus = this.getDataFromArr(this.projectObj.data.roles,row.uuid,'roleMenu');
                if(this.$refs['tree']){
                    this.$refs.tree.setCheckedKeys(this.menuDialog.roleHasMenus);
                }
            },
            insertOrUpdateRole:function() {
                var _this = this
                if (this.roleDialog.form.name == null || this.roleDialog.form.name == ''){
                    _this.$message({
                        message: '请输入角色名',
                        type: 'error'
                    });
                    return;
                }
                if (this.roleDialog.form.key == null || this.roleDialog.form.key == ''){
                    _this.$message({
                        message: '请输入角色KEY',
                        type: 'error'
                    });
                    return;
                }
                if (this.roleDialog.form.uuid){
                    this.messageTitle = '修改角色';
                    this.updateArrData(this.projectObj.data.roles,this.roleDialog.form.uuid,'roleName',{name:this.roleDialog.form.name,key:this.roleDialog.form.key});
                    this.saveCurrectProject();
                    this.roleDialog.roleVisible = false;
                }else {
                    this.$magicaltool.request.axios({
                        method: 'get',
                        url: '/magical_lowcode/manager/page/uuid',
                        param: {  }
                    }).then(function (res) {
                        if (res.code == 0){
                            _this.roleDialog.form.uuid = res.data
                            _this.updateArrData(_this.projectObj.data.roles,_this.roleDialog.form.uuid,'addRole',{name:_this.roleDialog.form.name,key:_this.roleDialog.form.key})
                            _this.messageTitle = '新增角色';
                            _this.saveCurrectProject();
                            _this.roleDialog.roleVisible = false;
                        }else {
                            _this.$message({
                                message: '获取uuid失败',
                                type: 'error'
                            });
                        }
                    });
                }
            },
            insertOrUpdatePermission:function(){
                const _this = this
                if (this.interfaceDialog.form.name == null || this.interfaceDialog.form.name == ''){
                    _this.$message({
                        message: '请输入接口名',
                        type: 'error'
                    });
                    return;
                }
                if (this.interfaceDialog.form.urlReg == null || this.interfaceDialog.form.urlReg == ''){
                    _this.$message({
                        message: '请输入接口地址',
                        type: 'error'
                    });
                    return;
                }
                if (this.interfaceDialog.form.uuid != null && this.interfaceDialog.form.uuid != ''){
                    this.messageTitle = '修改接口';
                    this.updateArrData(this.projectObj.data.permissions,this.interfaceDialog.form.uuid,'interfaceName',this.interfaceDialog.form.name);
                    this.saveCurrectProject();
                    this.interfaceDialog.permissionVisible = false;
                }else {
                    this.$magicaltool.request.axios({
                        method: 'get',
                        url: '/magical_lowcode/manager/page/uuid',
                        param: {  }
                    }).then(function (res) {
                        if (res.code == 0){
                            _this.interfaceDialog.form.uuid = res.data
                            _this.updateArrData(_this.projectObj.data.permissions,_this.interfaceDialog.form.uuid,'addInterface',_this.interfaceDialog.form.name);
                            _this.messageTitle = '新增接口';
                            _this.saveCurrectProject();
                            _this.interfaceDialog.permissionVisible = false;
                        }else {
                            _this.$message({
                                message: '获取uuid失败',
                                type: 'error'
                            });
                        }
                    });
                }
            },
            updateRolePermission:function() {
                this.updateArrData(this.projectObj.data.roles,this.permissionDialog.roleUuid,'rolePermissions',this.permissionDialog.hasPermissions)
                this.messageTitle = '修改权限';
                this.saveCurrectProject();
                this.permissionDialog.permissionVisible = false;
            },
            updateRoleMenu:function(){
                var res = this.$refs.tree.getCheckedKeys(true);//.concat(this.$refs.tree.getHalfCheckedKeys());
                var newRoleMenu = Array.from(new Set(res));
                this.updateArrData(this.projectObj.data.roles,this.menuDialog.roleUuid,'roleMenus',newRoleMenu)
                this.messageTitle = '修改菜单';
                this.saveCurrectProject();
                this.menuDialog.menuVisible = false;
            },
            selectRole:function(){
              if (this.roleForm.name != null && this.roleForm.name != ''){
                  this.roleData = this.projectObj.data.roles.filter(item => (item.name).indexOf(this.roleForm.name) > -1)
              }else {
                  this.roleData = this.projectObj.data.roles;
              }
            },
            selectPermission:function(){
                var permissionDatas = ''
                if (this.permissionForm.name != null && this.permissionForm.name != ''){
                    permissionDatas = this.projectObj.data.permissions.filter(item => (item.name).indexOf(this.permissionForm.name) > -1)
                }else {
                    permissionDatas = this.projectObj.data.permissions;
                }
                this.permissionData = this.getPagePermissionData(this.pageObj.currentPage,this.pageObj.pageSize,permissionDatas);
            },
            restRoleForm:function() {
                this.roleForm.name = ''
            },
            restPermissionForm:function(){
                this.permissionForm.name = ''
            },
            handleSizeChange:function(){
                this.permissionData = this.getPagePermissionData(this.pageObj.currentPage,this.pageObj.pageSize,this.projectObj.data.permissions);
            },
            handleCurrentChange:function(){
                this.permissionData = this.getPagePermissionData(this.pageObj.currentPage,this.pageObj.pageSize,this.projectObj.data.permissions);
            },
            // 数组中拿到指定返回字段
            getDataFromArr:function(arr,uuid,type){
                if (arr.length > 0){
                    for (var i = 0; i< arr.length; i++){
                        if (arr[i].uuid == uuid){
                            if (type == 'rolePermissions'){
                                return arr[i].permissionUuids;
                                break;
                            }else if(type == 'roleMenu'){
                                return arr[i].menuUuids;
                                break;
                            }
                        }
                    }
                }
            },
            // 替换数组中指定字段值
            updateArrData:function(arr,uuid,type,newValue){
                if(type == 'addRole') {
                    var obj = {
                        uuid: uuid,
                        name: newValue.name,
                        key: newValue.key,
                        menuUuids: [],
                        permissionUuids:[]
                    }
                    arr.push(obj)
                    return ;
                }
                if(type == 'addInterface') {
                    var obj = {
                        uuid: uuid,
                        name: newValue,
                        urlReg: this.interfaceDialog.form.urlReg
                    }
                    arr.push(obj)
                    return ;
                }
                if (arr.length > 0){
                    for (var i = 0; i< arr.length; i++){
                        if (arr[i].uuid == uuid){
                            if (type == 'rolePermissions'){
                                arr[i].permissionUuids = newValue
                                break;
                            }else if(type == 'roleName'){
                                arr[i].name = newValue.name
                                arr[i].key = newValue.key
                                break;
                            }else if(type == 'deleteRole'){
                                arr.splice(i,1)
                                break;
                            }else if(type == 'roleMenus') {
                                arr[i].menuUuids = newValue
                                break;
                            }else if(type == 'interfaceName'){
                                arr[i].name = newValue
                                arr[i].urlReg = this.interfaceDialog.form.urlReg
                                break;
                            }else if(type == 'deletePermission'){
                                arr.splice(i,1)
                                break;
                            }
                        }
                    }
                }
            },
            // 替换json 对象中 属性
            updateJsonPro:function(json,pro,newPro,pro1,newPro1){
                if (pro == 'name' && pro1 == 'uuid'){
                    return JSON.parse(JSON.stringify(json).replace(/name/g, newPro).replace(/uuid/g, newPro1));
                }else if (pro == 'label' && pro1 == 'id'){
                    return JSON.parse(JSON.stringify(json).replace(/label/g, newPro).replace(/id/g, newPro1));
                }
            },
            // 获取所有菜单父节点
            getAllFatherTreeNode:function(tree){
                var fnode = [];
                if (tree.length > 0){
                    for (var i = 0; i < tree.length; i++){
                        fnode.push(tree[i].id)
                    }
                }
                return fnode;
            },
            // 保存项目信息
            saveProjectInfo:function(){
                const _this = this;
                this.$magicaltool.request.axios({
                    method: 'post',
                    url: '/magical_lowcode/manager/page/save',
                    param: {
                        projectUuid: this.projectObj.projectUuid,
                        data: JSON.stringify(this.projectObj.data)
                    }
                }).then(function (res) {
                    if (res.code == 0){
                        _this.$message({
                            message: _this.messageTitle+'成功',
                            type: 'success'
                        });
                        _this.getProject();
                    }else{
                        _this.$message({
                            message: _this.messageTitle+'失败',
                            type: 'error'
                        });
                    }
                });
            },
            // es6 接口数据分页
            getPagePermissionData:function(page, pageSize, array){
                // 获取总数
                this.pageObj.total = array.length;
                // 进行分页
                var pageCount = page * pageSize;
                var pagepev = (page - 1) * pageSize;
                let data= array.filter((item, index) => {
                    return index < pageCount && index >= pagepev
                });
                return data;
            },
            // 移除对象属性
            updateObjData:function(obj,pro){
                if (pro == 'menus'){
                    delete obj.menus;
                }
            },
            // 保存逻辑
            saveCurrectProject:function(){
                this.updateJsonPro(this.projectObj.data.menus,'name','label','uuid','id');
                // 处理项目数据 项目中所有菜单数据单独维护
                this.updateObjData(this.projectObj.data,'menus');
                this.saveProjectInfo();
            },
            tableRowClassName:function(scope) {
                var rowIndex = scope.rowIndex;
                if (rowIndex % 2 == 1) {
                    return 'warning-row';
                } else if (rowIndex % 2 == 0) {
                    return 'success-row';
                }
                return '';
            }
        }
    });
    new Ctor().$mount('#magicalDragScene');

</script>
<style>
    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }
    #magicalDragScene{
        background-color:#fff;
        padding:15px;
    }
</style>
</body>

</html>
